package cerebrum.common;

import cerebrum.entity.ThreadEntity;

public class ThreadUtil {
    /**
     * 根据线程名称关闭线程
     *
     * @param name
     * @return
     */
    public static boolean killThreadByName(String name) {

        ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();

        int noThreads = currentGroup.activeCount();

        Thread[] lstThreads = new Thread[noThreads];

        currentGroup.enumerate(lstThreads);

        for (int i = 0; i < noThreads; i++) {

            String nm = lstThreads[i].getName();
            if (nm.equals(name)) {
                lstThreads[i].stop();

                return true;

            }

        }

        return false;

    }

    /**
     * 自定义缓存
     */
    static volatile ThreadEntity threadEntity;

    /**
     * 名称，运行状态
     * @param name
     * @param taskStatus
     */
    public static void threadCacheInit(String name, boolean taskStatus) {
        threadEntity = new ThreadEntity();
        threadEntity.setName(name);
        threadEntity.setTaskStatus(taskStatus);
    }

    //设置壁纸任务停止状态
    public static void killTask() {
        threadEntity.setTaskStatus(false);
    }
    //设置壁纸任务状态
    public static void setTaskStatus(boolean status) {
        if (EmptyChecker.isEmpty(threadEntity)){
            String name = Thread.currentThread().getName();
            threadCacheInit(name,status);
            return;
        }
        threadEntity.setTaskStatus(status);
    }
    public static boolean getTaskStatus() {
        return threadEntity.getTaskStatus();
    }

    public static String getName(){
        try {
            return threadEntity.getName();
        }catch (Exception e){//没初始化会空指针
            return null;
        }

    }
}
